//
//  YHStatusPictureView.swift
//  YHWeibo
//
//  Created by 昱含 on 16/5/25.
//  Copyright © 2016年 YuHan. All rights reserved.
// 显示微博配图视图

import UIKit

private let pictureMargin: CGFloat = 3
private let maxWidth = screenWidth - 2 * StatusCellMargin
private let itemWidth = (maxWidth - 2 * pictureMargin) / 3
private let pictureCellID = "pictureCellID"

class YHStatusPictureView: UICollectionView {

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let layout = UICollectionViewFlowLayout()
        
        layout.minimumLineSpacing = pictureMargin
        
        layout.minimumInteritemSpacing = pictureMargin
        
        super.init(frame: frame, collectionViewLayout: layout)
        
        self.dataSource = self
        
        self.delegate = self
        
        backgroundColor = UIColor.whiteColor()
        
        //点击状态栏回到顶部设置
        scrollsToTop = false
        
        registerClass(YHStatusPictureCell.self, forCellWithReuseIdentifier: pictureCellID)
        
        setupUI()
    
    }
    
    private func setupUI() {
        addSubview(testLabel)
        testLabel.snp_makeConstraints { (make) in
            make.center.equalTo(self.snp_center)
        }
    }
    
    private lazy var testLabel: UILabel = UILabel(title: "", font: 30, textColor: UIColor.greenColor())
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    var pictures: [YHPicture]? {
        
        didSet {
            
            testLabel.text = "\(pictures?.count ?? 0)"
//            print(pictures?.count)
            let pSize = calculatePictureViewSize()
            self.snp_updateConstraints { (make) in
                make.size.equalTo(pSize)
            }
            
            reloadData()
        }
    }
    
    func calculatePictureViewSize() -> CGSize {
        
        let imageCount = pictures?.count ?? 0
        
        if imageCount == 0 {
            
            return CGSizeZero
        }
        
        let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        if imageCount == 1 {
            
            let imageSize = CGSizeMake(100, 150)
            
            layout.itemSize = imageSize
            
            return imageSize
            
        }
        
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        
        if imageCount == 4 {
            
            let w = itemWidth * 2 + pictureMargin
            
            return CGSizeMake(w, w)
        }
        
        let row = CGFloat((imageCount - 1) / 3) + 1
        
        let maxHeight = row * itemWidth + (row - 1) * pictureMargin
        
        return CGSizeMake(maxWidth, maxHeight)
        
    }

}

extension YHStatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pictures?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(pictureCellID, forIndexPath: indexPath) as! YHStatusPictureCell
        
        cell.backgroundColor = randomColor()
        
        cell.picture = pictures![indexPath.row]
        
        return cell
        
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self
        browser.imageCount = pictures?.count ?? 0
        browser.currentImageIndex = indexPath.item
        browser.delegate = self
        browser.show()
    }
}

extension YHStatusPictureView: SDPhotoBrowserDelegate {
    
    func photoBrowser(browser: SDPhotoBrowser!, placeholderImageForIndex index: Int) -> UIImage! {
        let indexPath = NSIndexPath(forItem: index, inSection: 0)
        let cell = cellForItemAtIndexPath(indexPath) as! YHStatusPictureCell
        return cell.imageView.image
        
    }
    
    func photoBrowser(browser: SDPhotoBrowser!, highQualityImageURLForIndex index: Int) -> NSURL! {
        let urlString = pictures![index].thumbnail_pic
        let middleURLString = urlString?.stringByReplacingOccurrencesOfString("thumbnail", withString: "bmiddle")
        let url = NSURL(string: middleURLString!)
        return url
        
    }
}

    class YHStatusPictureCell: UICollectionViewCell {
        
        var picture: YHPicture? {
            
            didSet{
                
                let url = NSURL(string: picture?.thumbnail_pic ?? "")
                
                imageView.sd_setImageWithURL(url)
                
            }
        }
        
        override init(frame: CGRect) {
            super.init(frame: frame)
            setupUI()
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
        
        private func setupUI() {
            
           contentView.addSubview(imageView)
            
            imageView.snp_makeConstraints { (make) in
                make.edges.equalTo(contentView.snp_edges)
            }
            
        }

    
        private lazy var imageView: UIImageView = {
            let iv = UIImageView()
            iv.contentMode = .ScaleAspectFill
            iv.clipsToBounds = true
            return iv
        }()

}

